<template>
  <!-- 顶部内容, 书写在这里, 通过传送门(teleporter) 放在顶部内 -->
  <teleport to=".header">
    <SdyHeader title="登录" />
  </teleport>

  <div class="login-box">
    <van-form @submit="submitHandler" class="login-form">
      <van-cell-group inset>
        <van-field
          v-model="userInfo.loginname"
          name="loginname"
          label="用户名"
          placeholder="用户名"
          autocomplete="off"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <div class="item">
          <van-field
            v-model="userInfo.password"
            :type="pwdVisited ? 'text' : 'password'"
            name="password"
            label="密码"
            placeholder="密码"
            autocomplete="off"
            :rules="[{ required: true, message: '请填写密码' }]" />
            <van-icon @click="pwdVisited = false" v-if="pwdVisited" class="eye" name="eye-o" />
            <van-icon @click="pwdVisited = true" v-else class="eye" name="closed-eye" />
        </div>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>

    <van-divider :style="{ borderColor: '#1989fa', width: '100%' }">其他</van-divider>

    <p>还没有账号, <router-link to="/register">去注册</router-link></p>
  </div>
</template>

<script name="sdyLogin" lang="ts" setup>
import SdyHeader from '../../components/header.vue'
import { ref } from 'vue'
import { login } from '../../model/users'
import { showSuccessToast, showFailToast } from 'vant'
import { useRouter } from 'vue-router'

const $myRouter = useRouter()

interface User {
  loginname: string
  password: string
}


interface ResponseInfo {
  code: string
  data?: {
    token: string
    userid: string
  },
  message: string
}

// 准备数据采集用户信息
const userInfo = ref<User>({ loginname: '', password: '' })

// 准备一个变量表示 密码的可视程度
const pwdVisited = ref<boolean>(false)

// 表单提交事件
const submitHandler = async (info: User) => {
  const res = await login(info)
  if ((res as unknown as ResponseInfo).code === '10011') {
    showFailToast('密码错误')
    return
  }

  if ((res as unknown as ResponseInfo).code === '10010') {
    showFailToast('该用户不存在')
    return
  }

  showSuccessToast('登录成功')

  // 把用户 id 的 token 存储起来
  window.localStorage.setItem('token', res.data.token)
  window.localStorage.setItem('user_id', res.data.userid)

  // 页面跳转了
  $myRouter.back()
}
</script>

<style scoped lang="scss">
.login-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  > .login-form {
    border: 1px solid #333;
    border-radius: 10px;

    .item {
      position: relative;

      > .eye {
        position: absolute;
        right: 10px;
        top: 15px;
      }
    }
  }
}
</style>
